<template>
  <div class="mod-user">
    <div class="mod-unit-tree">
      <el-form size="small" :model="queryForm">
        <el-form-item>
          <el-input v-model="queryForm.unitName" placeholder="单位名称" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-tree
            :data="unitList"
            :props="unitListTreeProps"
            node-key="id"
            ref="unitListTree"
            @node-click="nodeClick"
            :highlight-current="true"
            :expand-on-click-node="false"
            :default-expand-all="true"
            :filter-node-method="searchUnitNode"
          ></el-tree>
        </el-form-item>
      </el-form>
    </div>
    <div class="mod-user-table">
      <el-form size="small" :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
        <el-form-item>
          <el-input v-model="dataForm.userName" placeholder="用户名" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="getDataList()">查询</el-button>
          <el-button type="primary" @click="addOrUpdateHandle()">新增</el-button>
          <el-button type="primary" @click="exportExcel()">导出</el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="dataList"
        size="mini"
        row-key="id"
        border
        v-loading="dataListLoading"
        @selection-change="selectionChangeHandle"
        style="width: 100%"
      >
        <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
        <el-table-column type="index" align="center" label="编号" width="80" />
        <el-table-column prop="username" header-align="center" align="center" label="用户名"></el-table-column>
        <el-table-column prop="nickName" header-align="center" align="center" label="姓名"></el-table-column>
        <el-table-column prop="phone" header-align="center" align="center" width="100" label="手机号"></el-table-column>
        <el-table-column prop="email" header-align="center" align="center" width="180" label="邮箱"></el-table-column>

        <el-table-column
          prop="id"
          header-align="center"
          align="center"
          width="150"
          :show-overflow-tooltip="true"
          label="角色名称"
        >
          <template slot-scope="scope">
            <el-tag
              v-for="item in scope.row.roleNames"
              :key="item"
              size="small"
              effect="plain"
              type="success"
            >{{ item }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="dataState" header-align="center" align="center" label="状态">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.dataState === -1" size="small" type="danger">禁用</el-tag>
            <el-tag v-else size="small">正常</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          header-align="center"
          align="center"
          width="180"
          label="创建时间"
        ></el-table-column>
        <el-table-column fixed="right" header-align="center" align="center" width="200" label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="resetPassword(scope.row.id)">重置密码</el-button>

            <el-button type="text" size="small" @click="addOrUpdateHandle(scope.row)">修改</el-button>
            <el-button type="text" size="small" @click="deleteHandle(scope.row.id)">删除</el-button>
            <el-button
              v-if="scope.row.dataState === -1"
              type="text"
              size="small"
              @click="enableHandle(scope.row.id)"
            >启用</el-button>
            <el-button
              v-if="scope.row.dataState === 0"
              type="text"
              size="small"
              @click="disableHandle(scope.row.id)"
            >冻结</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="pageIndex"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        :total="totalPage"
        layout="total, sizes, prev, pager, next, jumper"
      ></el-pagination>
    </div>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
  </div>
</template>

<script>
import AddOrUpdate from "./user-add-or-update";
import { pageList as pageUnitList } from "@/api/unit";
import {
  pageList as pageUserList,
  enable,
  disable,
  resetPassword,
  remove
} from "@/api/user";
import { treeDataTranslate } from "@/utils";
export default {
  data() {
    return {
      queryForm: {
        unitName: ""
      },
      dataForm: {
        userName: "",
        unitId: ""
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      unitList: [],
      unitListTreeProps: {
        label: "name",
        children: "children"
      }
    };
  },
  watch: {
    "queryForm.unitName": function(val) {
      this.$refs.unitListTree.filter(val);
    }
  },
  components: {
    AddOrUpdate
  },
  activated() {
    this.getUnitList();
  },
  methods: {
    searchUnitNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    nodeClick(data, node) {
      console.log(data);
      this.dataForm.unitId = data.id;
      this.getDataList();
    },
    // 获取单位数据列表
    getUnitList() {
      pageUnitList({})
        .then(res => {
          if (res && res.code === 0) {
            this.unitList = treeDataTranslate(res.data, "id");
          }
        })
        .then(res => {
          if (this.unitList.length) {
            this.dataForm.unitId = this.unitList[0].id;
            this.unitListTreeSetCurrentNode();
          }
        })
        .then(res => {
          this.getDataList();
        });
    },
    // 菜单树设置当前选中节点
    unitListTreeSetCurrentNode() {
      this.$refs.unitListTree.setCurrentKey(this.dataForm.unitId);
      this.dataForm.parentName = (this.$refs.unitListTree.getCurrentNode() ||
        {})["name"];
    },
    // 获取数据列表
    getDataList() {
      this.dataListLoading = true;
      pageUserList({
        pageNumber: this.pageIndex,
        pageSize: this.pageSize,
        username: this.dataForm.userName,
        unitId: this.dataForm.unitId
      }).then(res => {
        if (res && res.code === 0) {
          this.dataList = res.data.data;
          this.totalPage = res.data.data.count;
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      });
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getDataList();
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val;
    },
    // 新增 / 修改
    addOrUpdateHandle(data) {
      this.addOrUpdateVisible = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(data);
        this.$refs.addOrUpdate.setUnitId(this.dataForm.unitId);
      });
    },
    enableHandle(id) {
      this.$confirm(`确定进行启用操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          enable({ id: id }).then(res => {
            if (res && res.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1000,
                onClose: () => {
                  this.getDataList();
                }
              });
            } else {
              this.$message.error(res.msg);
            }
          });
        })
        .catch(() => {});
    },
    disableHandle(id) {
      this.$confirm(`确定进行冻结操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          disable({ id: id }).then(res => {
            if (res && res.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1000,
                onClose: () => {
                  this.getDataList();
                }
              });
            } else {
              this.$message.error(res.msg);
            }
          });
        })
        .catch(() => {});
    },
    resetPassword(id) {
      this.$confirm(`是否确定进行重置密码操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          resetPassword({ id: id }).then(res => {
            if (res && res.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1000,
                onClose: () => {
                  this.getDataList();
                }
              });
            } else {
              this.$message.error(res.msg);
            }
          });
        })
        .catch(() => {});
    },
    exportExcel() {
      this.$message.error("开发中");
    },
    // 删除
    deleteHandle(id) {
      var ids = id
        ? [id]
        : this.dataListSelections.map(item => {
            return item.id;
          });

      this.$confirm(`是否确定进行删除操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          remove({ ids: ids }).then(res => {
            if (res && res.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1000,
                onClose: () => {
                  this.getDataList();
                }
              });
            } else {
              this.$message.error(res.msg);
            }
          });
        })
        .catch(() => {});
    }
  }
};
</script>

<style lang="scss">
.mod-user {
  position: relative;
}

.mod-user .mod-unit-tree {
  position: relative;
  width: 230px;
  min-height: 100%;
  height: 100%;
  float: left;
}
.mod-user .mod-user-table {
  position: relative;
  margin-left: 235px;
  min-height: 100%;
  top: 0px;
}
</style>